package com.demo.search;

import java.io.IOException;

import org.apache.commons.codec.language.Metaphone;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;

/**
 * 等效音素替换语汇单元
 * @author ryuu.kk
 *
 */
public class MetaphoneReplacementFilter extends TokenFilter {

	public static final String METAPHONE = "metaphone";
	private Metaphone meaphoner = new Metaphone();
	private CharTermAttribute charTermAttr;
	private TypeAttribute typeAttr;
	private PositionIncrementAttribute posIncrAtt;

	public MetaphoneReplacementFilter(TokenStream input) {
		super(input);
		charTermAttr = addAttribute(CharTermAttribute.class);
		typeAttr = addAttribute(TypeAttribute.class);
		posIncrAtt = addAttribute(PositionIncrementAttribute.class);
	}

	@Override
	public boolean incrementToken() throws IOException {

		if (!input.incrementToken()) return false;
		
		String encoded = "";
		String chatContent = charTermAttr.toString();
		
		char[] charArray = chatContent.toCharArray();
		boolean isChinese = true;
		for (char c : charArray) {
			// 非中文字符
			if (c < 0x4e00 || c > 0x9fbb) {
				isChinese = false;
				break;
			}
		}
		if (isChinese) {
			encoded = chatContent;
		} else {
			// 英文字符
			// 取得读音
			encoded = meaphoner.encode(chatContent);
		}
		charTermAttr.setEmpty();
		charTermAttr.append(encoded);
		
		typeAttr.setType(METAPHONE);
		return true;
	}

}
